#include "StdAfx.h"
#include "ChCSettings.h"

CChCSettings* CChCSettings::s_pInstance = NULL;

CChCSettings::CChCSettings(void)
{
	m_strHostName			= _T("127.0.0.1");
	m_uPort					= 21000;
	m_ColorSystemMessages	= 255;
	m_ColorFromMessages		= 0;
	m_ColorToMessages		= 0;
}

CChCSettings::~CChCSettings(void)
{
}

CChCSettings* CChCSettings::Instance()
{
	return s_pInstance;
}

BOOL CChCSettings::Initialize()
{
	if(NULL == s_pInstance)
		s_pInstance = new CChCSettings;

	return s_pInstance->ReadSetings();
}

void CChCSettings::Uninitialize()
{
	if(NULL != s_pInstance)
	{
		s_pInstance->SaveSettings();
		delete s_pInstance;
		s_pInstance = NULL;
	}
}

BOOL CChCSettings::ReadSetings()
{
	try
	{
		CFile _file;
		if(TRUE == _file.Open(CLIENT_SETTINGS_FILE_NAME,CFile::modeRead))
		{
			CArchive _arch(&_file,CArchive::load);
			Serialize(_arch);
			_arch.Close();
			_file.Close();
			return TRUE;
		}
		else
		{
			AfxMessageBox(_T("Can't find file with settings. Use defoult settings."));
			return FALSE;
		}
	}
	catch (CMemoryException* e)
	{
		e->ReportError();
		AfxMessageBox(_T("Can't find file with settings. Use defoult settings."));
		return FALSE;
	}
	catch (CFileException* e)
	{
		e->ReportError();
		AfxMessageBox(_T("Can't find file with settings. Use defoult settings."));
		return FALSE;
	}
	catch (CException* e)
	{
		e->ReportError();
		AfxMessageBox(_T("Can't find file with settings. Use defoult settings."));
		return FALSE;
	}
}

BOOL CChCSettings::SaveSettings()
{
	try
	{
		CFile _file;
		if(TRUE == _file.Open(CLIENT_SETTINGS_FILE_NAME,CFile::modeWrite|CFile::modeCreate))
		{
			CArchive _arch(&_file,CArchive::store);
			Serialize(_arch);
			_arch.Close();
			_file.Close();
			return TRUE;
		}
		else
		{
			AfxMessageBox(_T("Can't find file with settings. Use defoult settings."));
			return FALSE;
		}
	}
	catch (CMemoryException* e)
	{
		e->ReportError();
		AfxMessageBox(_T("Can't find file with settings. Use defoult settings."));
		return FALSE;
	}
	catch (CFileException* e)
	{
		e->ReportError();
		AfxMessageBox(_T("Can't find file with settings. Use defoult settings."));
		return FALSE;
	}
	catch (CException* e)
	{
		e->ReportError();
		AfxMessageBox(_T("Can't find file with settings. Use defoult settings."));
		return FALSE;
	}
}

void CChCSettings::Serialize(CArchive &ar)
{
	if(ar.IsLoading())
	{
		ar>>m_strHostName;
		ar>>m_uPort;
		ar>>m_ColorSystemMessages;
		ar>>m_ColorFromMessages;
		ar>>m_ColorToMessages;
		ar>>m_ColorToAllMessages;
	}
	else
	{
		ar<<m_strHostName;
		ar<<m_uPort;
		ar<<m_ColorSystemMessages;
		ar<<m_ColorFromMessages;
		ar<<m_ColorToMessages;
		ar<<m_ColorToAllMessages;
	}
}